<template>
  <!-- <template slot="right">
      <span class="hintRight">08:09:48后订单关闭</span>
    </template>
    <div class="pay pd30">
      <div class="pay_main">
        <el-row>
          <slot name="detail"></slot>
        </el-row> -->

  <el-row>
    <el-col :span="24">
      <el-tabs @tab-click="clickFn" type="card" v-model="activeName" :class="getQrCode(nowCircle)?'':'noErcode'">
        <el-tab-pane label="问金支付" name="askGold">
          <ul class="askGold">
            <li v-for="item in addedCircleList" :key="item.id">
              <el-avatar :size="40" :src="item.avatar || circleUrl"></el-avatar>
              <div class="askInfo">
                <div>
                  <h3>{{ item.nickname }}</h3>
                  <p v-if="getUnusableCause(item)">不可用原因：仅能用首次支付的圈子支付</p>
                  <p v-else>
                    余额: {{ item.balance || 0 }}问金
                    <span v-if="getBalance(item.balance)">
                      {{ getBalance(item.balance) ? "余额不足" : "" }}
                      <el-button @click="goTopUp()" round size="mini">
                        充值
                      </el-button>
                    </span>
                  </p>
                </div>
                <el-radio @change="selectdefaultPayFn(item)" v-model="item.defaultPay" label="1"
                  :disabled="getProjectState(item)"></el-radio>
              </div>
            </li>
          </ul>
        </el-tab-pane>
        <!-- getAmountState获取扫码支付状态 0金额的时候 -->
        <el-tab-pane label="扫码支付" name="scanQr" v-if="getQrCode(nowCircle)" :disabled="getAmountState()">
          <div class="scanQr">
            <!-- v-if="emailState()" -->
            <img :src="scanQr" alt="" />
            <!-- <div v-else class="rulEmailTxt">请输入有效的邮箱</div> -->
            <p>应付问金： {{ getPayAmount() | sumFilters }}</p>
            <span>微信扫码支付</span>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
</template>

<script>
  import NewCard from "@/wss/components/newCard.vue";
  import { getCircleUpdateDefaultPayApi } from "@/BMViews/api/service/circle.js";
  import { getCircleSelectCircleAmountApi } from "@/BMViews/api/service/circle.js";
  import { depositWxPayApi, createDepositOrderApi } from "@/BMViews/api/financial/deposit.js";
  import { getcircleuserListApi } from "@/BMViews/api/financial/deposit.js";
  import { getselectCircleAmountApi } from "@/BMViews/api/service/circle.js";
  import debounce from "lodash/debounce";
  export default {
    name: "Pay",
    props: {
      // true不需要扫码 false需要扫码
      noQrcode: {
        type: Boolean,
        default: false
      },
      orderinfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      nextFlowId: {
        type: String,
      },
      // 电邮邮箱
      email: {
        type: String,
      },
      // 接收信息邮箱
      acceptEmail: {
        type: String,
      },
      // 判断是否是电邮，默认不是
      isEmailOrDown: {
        type: Boolean,
        default: () => {
          return false
        },
      },
    },
    components: { NewCard },
    data() {
      return {
        isright: true, //显示时间提示支付
        // email: "", //邮件
        // acceptEmail: "12345678@wensanshi.cn", //接收邮箱
        activeName: "askGold", //默认显示问金支付
        circleUrl:
          "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png", //头像
        askRadio: "1",
        // 圈圈主列表
        CircleList: [],
        scanQr: "~@/assets/images/er.png",
        // 充值的定时器
        timer: "",
        // 已加入的圈子
        addedCircleList: [],
        nowCircle: {},//当前选中的圈子
      };
    },
    created() {
      // this.getCircleSelectCircleAmountFn();
      // this.$bus.$off("EventPaymentCompletion");
      this.$bus.$off("updatePayCircle");
      // 圈子那边删除动态更新圈子
      this.$bus.$on("updatePayCircle", () => {
        this.getSelectJoinCircleFn();
      });
      this.getSelectJoinCircleFn();
    },

    beforeDestroy() {
      // 消除定时器
      clearInterval(this.timer);
    },

    computed: {
      getBalance() {
        return (balance) => {
          return this.orderinfo.amount > (balance || 0) ? true : false;
        };
      },
    },

    methods: {
      // 选择默认支付
      async selectdefaultPayFn(item) {
        this.nowCircle = item //获取当前选中的圈子
        let { code, msg } = await getCircleUpdateDefaultPayApi(item);
        if (code != 200) return;
        // this.$message({
        //   type: "success",
        //   message: msg,
        // });
        this.addedCircleList.forEach((v) => {
          if (v.circleId == item.circleId) {
            v.defaultPay = "1";
          } else {
            v.defaultPay = "0";
          }
        });

        this.getSelectJoinCircleFn();
      },

      // 获取项目支付状态
      getProjectState(item) {
        if (this.orderinfo.type == "6") {
          // 项目的  有圈主id才判断
          if (this.orderinfo.circleId) {
            // 订单的圈主id等于当前的圈主id 才能支付
            if (this.orderinfo.circleId != item.circleId) {
              return true;
            } else {
              return false;
            }
          } else {
            return false; //没有圈子id的时候
          }
        } else {
          // 其他的
          return this.orderinfo.amount > (item.balance || 0) ? true : false;
        }
      },

      // 获取 不可用原因：仅能用首次支付的圈子支付
      getUnusableCause(item) {
        if (this.orderinfo.type == "6") {
          // 项目的  有圈主id才判断
          if (this.orderinfo.circleId) {
            // 订单的圈主id等于当前的圈主id 才能支付
            if (this.orderinfo.circleId != item.circleId) {
              return true; //圈子id等于订单里的圈子id 说明当前选中的这个是第一次支付的圈子
            } else {
              return false; //圈子id不等于订单里的圈子id 说明当前选中的这个不是第一次支付的圈子
            }
          } else {
            return false; //没有圈子id的时候
          }
        } else {
          return false //不是项目
        }
      },

      // 获取当前扫码金额
      getPayAmount() {
        if (this.orderinfo.type == "6") {
          // 项目的金额要算一下
          if (this.orderinfo.goods) {
            let flows = this.orderinfo.goods.flows;
            let nowFlow = {}
            for (let i = 0; i < flows.length; i++) {
              if (flows[i].isPaid == false && flows[i].scale) {
                nowFlow = flows[i]
                return ((nowFlow.scale / 100) * this.orderinfo.goods.amount)
              }
            }
            return
          }
        } else {
          return this.orderinfo.amount
        }
      },

      // 获取项目扫码支付状态
      getQrCode(item) {
        // 不需要扫码
        if (this.noQrcode) {
          return false
        }
        if (this.orderinfo.type == "6") {
          // 项目的 有圈主id才判断
          if (this.orderinfo.circleId != this.$store.state.user.circleId) {
            return false; //圈子id等于订单里的圈子id 说明当前选中的这个是第一次支付的圈子
          } else {
            return true; //圈子id不等于订单里的圈子id 说明当前选中的这个不是第一次支付的圈子
          }
        } else {
          // 其他的
          return true
        }
      },

      // 获取当前扫码支付状态
      getAmountState() {
        // 项目的金额要算一下
        if (this.orderinfo.goods) {
          let flows = this.orderinfo.goods.flows;
          let nowFlow = {}
          for (let i = 0; i < flows.length; i++) {
            if (flows[i].isPaid == false && flows[i].scale) {
              nowFlow = flows[i]
              let nowAmount = ((nowFlow.scale / 100) * this.orderinfo.goods.amount)
              if (nowAmount == 0 || nowAmount == NaN) {
                return true //不可点击
              } else {
                return false //可点击
              }
            }
          }
        }
      },

      // 没有绑定邮箱的话就不给点击扫码支付
      emailState() {
        let reg = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        // 是扫码登录的时候才去判断
        if (this.activeName == 'scanQr') {
          if (this.isEmailOrDown) {
            // 是电邮
            if (!reg.test(this.email)) {
              // this.$message({ type: "warning", message: "请输入有效的邮箱！" });
              return false
            } else {
              return true
            }
          } else {
            //不是电邮
            if (!reg.test(this.acceptEmail)) {
              // this.$message({ type: "warning", message: "请输入有效的邮箱！" });
              return false
            } else {
              return true
            }
          }
        }

      },

      getCirecleDefaultPay() {
        const addedCircleList = this.addedCircleList;
        const circleId = addedCircleList.find(
          (item) => item.defaultPay == 1
        )?.circleId;
        const arr = [null, undefined, ""];

        if (arr.includes(circleId)) {
          this.$message({
            type: "warning",
            message: "请选中使用那个圈子支付",
          });
          return;
        }
        return circleId;
      },

      // 获取所加入的圈子
      async getSelectJoinCircleFn() {
        let myself = true;
        let { code, rows } = await getselectCircleAmountApi({ myself });
        if (code != 200) return;
        const addedCircleList = JSON.parse(JSON.stringify(rows)) || [];
        this.addedCircleList = addedCircleList || [];

        // 获取当前选中的圈子
        this.nowCircle = this.addedCircleList.find(item => {
          return item.defaultPay == '1'
        })
      },

      // tab切换时
      async clickFn({ name }) {

        // 如果是scanQr，必须要填写邮箱 ----------------
        // if(name == 'scanQr' && this.email == ''){
        //   this.$message({message: "请填写邮箱！",type: "warning"});
        //   return
        // }
        // 如果是scanQr，必须要填写邮箱 ----------------end
        // 当切换到二维码支付的时候要隐藏底部的按钮
        this.$bus.$emit("hidePayBtn", name);
        console.log(this.orderinfo, "过来了吗");

        // 如果为空或者订单id相同直接退出
        if (!this.orderinfo.id || this.orderinfo.id == this.orderId) return;
        // if (!this.emailState()) return;

        this.orderId = this.orderinfo.id;
        if ("scanQr" == name) {
          let orderRes = await this.addCreateDocOrder()

          //先创建消费充值订单   
          let data = {
            id: orderRes.id,
            type: 'native',
          }
          let res = await depositWxPayApi(data)
          if (res.code == 200) {
            console.log(res, '产生回调的信息');
            this.scanQr = res.data.wxQrcode
          }








          // // 聚合支付的
          // let { QrCode = "~@/assets/images/er.png", order } =
          //   await getcirclemaster({
          //     id: this.orderinfo.id,
          //     type: "2",
          //     circleId: "",
          //     flowId: this.orderinfo.flowId, //项目需要的步骤id
          //     nextFlowId: this.nextFlowId, //项目需要的下一步骤id
          //     email: this.email || this.acceptEmail
          //   });

          // this.scanQr = QrCode;
          // 生成之前都清除上一个定时器
          clearInterval(this.timer);
          this.timer = setInterval(() => {
            this.verifyOrderFn(order);
          }, 5000);
        } else {
          // getDepositVoucherPayApi
        }
      },
      // 创建问金充值订单
      async addCreateDocOrder() {
        try {
          let circleId = this.$store.state.user.circleId
          let amount = this.getPayAmount()
          let argument = {
            amount,
            circleId
          }

          const res = await createDepositOrderApi(argument)
          return res.data
        } catch (error) {

        }
      },
      // 获取二维码 防抖
      getQrcodeFn: debounce(async function () {
        // 先判断邮箱
        let reg = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (this.isEmailOrDown) {
          if (!reg.test(this.email)) return
        } else {
          if (!reg.test(this.acceptEmail)) return
        }

        let { QrCode = "~@/assets/images/er.png", order } =
          await getcirclemaster({
            id: this.orderinfo.id,
            type: "2",
            circleId: "",
            flowId: this.orderinfo.flowId, //项目需要的步骤id
            nextFlowId: this.nextFlowId, //项目需要的下一步骤id
            email: this.email || this.acceptEmail
          });

        this.scanQr = QrCode;
        // 生成之前都清除上一个定时器
        clearInterval(this.timer);
        this.timer = setInterval(() => {
          this.verifyOrderFn(order);
        }, 5000);
      }, 600),

      // 判断是否支付成功
      async verifyOrderFn(order) {
        let { code, rows } = await getcircleuserListApi({ orderNo: order });
        if (code != 200) return;

        if (rows[0]?.status == 2) {
          this.$message({
            message: "支付成功",
            type: "success",
          });
          clearInterval(this.timer);//扫码支付成功关闭定时器
          this.$bus.$emit("EventPaymentCompletion"); //扫码支付成功后激活这个事件

          this.rechargeQr = "";
        }
      },

      // // 查询圈子圈主列表
      // async getCircleSelectCircleAmountFn() {
      //   let { code, rows } = await getCircleSelectCircleAmountApi();
      //   if (code != 200) return;
      //   let CircleList = JSON.parse(JSON.stringify(rows));
      //   this.CircleList = CircleList;
      //   console.log(CircleList);
      // },

      // 余额不足跳转问金充值
      goTopUp() {
        let status = 3
        this.$router.push({ path: '/Bm-personalCenter/myAskAround', query: { status } })
      },
    },
    // 出来
    watch: {
      orderinfo: {
        async handler(newVal, oldVal) {
          // 数据发生改变就回到问金支付
          this.activeName = "askGold";
        },
        deep: true,
      },

      // 监听电邮 邮箱正确的话就去获取二维码（获取之前清除之前的二维码）
      email(newValue, oldValue) {
        if (this.activeName == 'scanQr') {
          let _this = this
          let reg = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (reg.test(this.email)) {
            this.scanQr = ''
            setTimeout(() => {
              _this.getQrcodeFn()
            }, 500)
          } else {
            this.scanQr = ''
          }
        }
      },

      // 监听邮箱 邮箱正确的话就去获取二维码（获取之前清除之前的二维码）
      acceptEmail(newValue, oldValue) {
        if (this.activeName == 'scanQr') {
          let _this = this
          let reg = /^[A-Za-z0-9_\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
          if (reg.test(this.acceptEmail)) {
            this.scanQr = ''
            setTimeout(() => {
              _this.getQrcodeFn()
            }, 500)
          } else {
            this.scanQr = ''
          }
        }
      },
    },
  };
</script>

<style scoped>
  .hintRight {
    font-size: 14px;
    color: #f87a23;
  }

  ::v-deep .el-card__body {
    position: relative;
  }

  ul,
  p {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .pd30 {
    padding: 0 30px;
  }

  /* 支付信息 */
  .pay_main {
    margin-bottom: 70px;
    margin-top: 15px;
  }

  .pay_main .el-card {
    border-radius: 12px;
  }

  ::v-deep .pay_main .el-card__body {
    padding: 20px;
  }

  .pay_main h3 {
    margin: 0;
    margin-bottom: 12px;
    font-size: 16px;
    color: #333;
  }

  .pay_main p {
    font-size: 14px;
    color: #999;
    margin: 0;
    line-height: 24px;
  }

  .pay_main .el-row {
    margin-top: 15px;
  }

  ::v-deep .pay_main .el-row .el-input__inner {
    border-radius: 8px;
    height: 44px;
    line-height: 44px;
  }

  .pay_main .el-row .acceptEmail {
    border: 0;
    padding: 5px 0;
    margin: 7px 0;
    margin-right: 10px;
    font-size: 14px;
    color: #bababa;
    background: #fff;
    cursor: pointer;
  }

  .pay_main .el-row .acceptEmail:hover {
    color: #f87a23;
  }

  .pay_main .inputTitle {
    font-size: 18px;
    color: #333;
    margin-bottom: 15px;
  }

  .pay_main .inputTitle span {
    font-size: 14px;
    color: #999;
  }

  ::v-deep .pay_main .el-tabs__header {
    border: 0;
    margin-bottom: 24px;
  }

  ::v-deep .pay_main .el-tabs__nav {
    width: 100%;
    display: flex;
    justify-content: space-between;
    border: 0;
  }

  ::v-deep .pay_main .el-tabs__item {
    width: 49%;
    border-radius: 8px;
    text-align: center;
    font-size: 14px;
    border: 0;
    background-color: #fafafa;
  }

  ::v-deep .noErcode .el-tabs__item {
    flex: 1;
  }

  ::v-deep .el-tabs__item.is-active {
    background-color: #f1f3ff;
    color: #39486f !important;
  }

  ::v-deep .pay_main .el-tabs__item:hover {
    color: #39486f;
  }

  /* 内容详情列表 */
  .detailList {
    border-bottom: 1px solid #ecedf0;
    padding-bottom: 15px;
    margin-bottom: 30px;
  }

  .detailList li {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 15px;
  }

  .detailList li>span {
    display: block;
    width: 17%;
    font-size: 14px;
    color: #999;
  }

  .detailList li .detailPage {
    width: 83%;
  }

  .detailList li .detailPage>p {
    width: 100%;
    font-size: 14px;
    color: #222;
  }

  /* 支付 */
  .askGold {
    list-style: none;
    padding: 0;
    margin: 0;
    width: 100%;
  }

  .askGold li {
    display: flex;
    margin-bottom: 24px;
  }

  .askGold li .el-avatar {
    margin-right: 14px;
  }

  .askGold .askInfo h3 {
    margin-bottom: 5px;
    font-size: 16px;
    color: #333;
  }

  .askGold .askInfo {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ecedf0;
    padding-bottom: 24px;
  }

  .askGold .askInfo p {
    font-size: 12px;
    color: #666;
  }

  .askGold .askInfo button {
    color: #39486f;
    border-color: #39486f;
    padding: 5px 15px;
  }

  ::v-deep .askInfo .el-radio__label {
    display: none;
  }

  ::v-deep .askInfo .el-radio .el-radio__inner {
    width: 24px;
    height: 24px;
    border-color: #bbbbbb;
    background: #fff;
  }

  ::v-deep .askInfo .el-radio .is-disabled .el-radio__inner {
    background: #f2f2f2;
  }

  ::v-deep .askInfo .el-radio .is-checked .el-radio__inner {
    border-color: #f87a23;
    background: #f87a23;
  }

  ::v-deep .askInfo .el-radio__input.is-checked .el-radio__inner::after {
    content: "";
    width: 11px;
    height: 7px;
    border: 3px solid white;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 6px;
    left: 5px;
    vertical-align: middle;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
  }

  .payBtn {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 9;
    width: 100%;
    background-color: #fff;
    border-top: 1px solid #ecedf0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 30px;
  }

  .payBtn p {
    margin: 0;
    font-size: 14px;
  }

  .payBtn p>span {
    color: #f87a23;
    font-size: 16px;
  }

  .payBtn .el-button {
    background-color: #f87a23;
    border-color: #f87a23;
    color: #fff;
    font-size: 14px;
    padding: 10px 50px;
  }

  .payBtn .el-button:hover {
    opacity: 0.9;
  }

  .scanQr {
    text-align: center;
  }

  .scanQr img {
    width: 150px;
  }

  .scanQr p {
    color: #f87a23;
    font-size: 18px;
  }

  .scanQr span {
    font-size: 12px;
    color: #999;
  }

  .rulEmailTxt {
    font-size: 14px;
    margin: 30px 0;
  }
</style>